package com.baidu.videoseries.activity;

import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;

import com.baidu.videoseries.ToolbarActivity;
import com.baidu.videoseries.R;
import com.baidu.videoseries.constant.Config;
import com.baidu.videoseries.util.JumpUtils;
import com.baidu.videoseries.util.LogUtils;


import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;
import org.videolan.libvlc.MediaPlayer.Event;

import java.util.ArrayList;

public class VlcActivity extends ToolbarActivity implements SurfaceHolder.Callback {
    private ProgressBar loadingView;
    private SurfaceView videoSurface;
    private SurfaceHolder mSurfaceHolder;
    private SeekBar mSeekBar;
    private ImageButton mPlayButton;

    private LibVLC mLibVLC;
    private MediaPlayer mMediaPlayer;
    private Media mMedia;

    private GestureDetector mGestureDetector;
    private static final int MOVE_SPEED = 100;
    private boolean isPlaying = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vlc);
        setActionBarVisible(View.GONE);
//        setFabVisibility(View.GONE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        setTitle("VLCDemo");
        loadingView = (ProgressBar) findViewById(R.id.loading_view);
        videoSurface = (SurfaceView) findViewById(R.id.video_surface);
        mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
        mPlayButton = (ImageButton) findViewById(R.id.play_button);
        initView();
    }

    private void initView() {
        //init view
        mSeekBar.setOnSeekBarChangeListener(mSeekBarChangedListener);

        mSurfaceHolder = videoSurface.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setFormat(PixelFormat.RGBX_8888);
        mSurfaceHolder.setKeepScreenOn(true);
        //init gesture detector
        mGestureDetector = new GestureDetector(this, mGestureListener);
        //init player here
        ArrayList<String> args = new ArrayList<>();
        args.add("-vvv");
        mLibVLC = new LibVLC(this,args);
        mMediaPlayer = new MediaPlayer(mLibVLC);
        mMediaPlayer.setEventListener(mEventListener);
        mMedia = new Media(mLibVLC, Uri.parse(Config.Urls.VIDEO_HUHU));
        mMediaPlayer.setMedia(mMedia);
        mMedia.parseAsync();
        mMediaPlayer.setTitle(1);


        setOnFabClickListener(new OnFabClickListener() {
            @Override
            public void onFabClick(View v) {
                JumpUtils.simpleJump(VlcActivity.this, TestActivity.class);
            }
        });
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //bind surface
        mMediaPlayer.getVLCVout().setVideoView(videoSurface);
        mMediaPlayer.getVLCVout().attachViews();
        mMediaPlayer.setSpuDelay(2 * 1000);
        mMediaPlayer.play();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.e("---------------------onPause");
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) mMediaPlayer.stop();
    }


    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e("---------------------onResume");
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.play();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMedia.release();
            mLibVLC.release();
        }
    }

    /**
     * event listener
     */
    private MediaPlayer.EventListener mEventListener = new MediaPlayer.EventListener() {
        @Override
        public void onEvent(Event event) {
//            LogUtils.e("--" + event.type);
            switch (event.type) {
            case Event.Opening:
                LogUtils.e("--" + event.type + " :length=" + mMediaPlayer.getLength());
                break;
            case Event.Playing:
                loadingView.setVisibility(View.GONE);
                isPlaying = true;
                break;
            case Event.Stopped:
                isPlaying = false;
                break;
            case Event.TimeChanged:
                int progress = (int) (mMediaPlayer.getTime() / 1000);
                mSeekBar.setProgress(progress);
//                    LogUtils.e("time=" + mMediaPlayer.getTime());
                break;
            case Event.Vout:
                int length = (int) mMediaPlayer.getLength() / 1000;
                mSeekBar.setMax(length);
                if (!mMediaPlayer.isPlaying()) mMediaPlayer.play();
                LogUtils.e("Vout", " :length=" + mMediaPlayer.getLength());
                break;
            case Event.MediaChanged:
                mMediaPlayer.pause();
                break;
        }
    }
    };

    /**
     * seek bar changed listener
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarChangedListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                mMediaPlayer.setTime(progress * 1000);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (mMediaPlayer != null) mMediaPlayer.play();
        }
    };

    /**
     * gesture listener
     */
    private OnGestureListener mGestureListener = new OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            LogUtils.e("onDown" + "--------");
            showView();
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            LogUtils.e("onShowPress" + "--------");
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            LogUtils.e("onSingleTapUp" + "--------");
            singleTopEvent();
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            LogUtils.e("onScroll" + "--------" + e2.getAction());
            long progress = (long) (mMediaPlayer.getTime() - distanceX * MOVE_SPEED);
            if (progress >= 0 && progress <= mSeekBar.getMax() * 1000) {
                mMediaPlayer.setTime(progress);
            }
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            LogUtils.e("onLongPress" + "--------");

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            LogUtils.e("onFling" + "--------");
            hideView();
            return true;
        }
    };

    private void singleTopEvent() {
        this.mPlayButton.setVisibility(View.VISIBLE);
        if (isPlaying) {
            mMediaPlayer.pause();
            mPlayButton.setBackgroundResource(R.mipmap.icon_pop_play);
            isPlaying = false;
        } else {
            mMediaPlayer.play();
            mPlayButton.setBackgroundResource(R.mipmap.icon_pop_pause);
            isPlaying = true;
        }
        hideView();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    /**
     * hide view
     */

    private void hideView() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPlayButton.setVisibility(View.INVISIBLE);
                mSeekBar.setVisibility(View.INVISIBLE);
            }
        }, 5 * 1000);

    }

    /**
     * show view and change pictures
     */
    private void showView() {
        this.mSeekBar.setVisibility(View.VISIBLE);
    }

    /**
     * use for update view
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
}
